# __HEADER__

"""XXX"""

import ldap.ldapobject
import threading

_connections = threading.local()

LDAP_URI = 'ldap:///'
LDAP_USER_DN = 'cn=Manager,dc=example,dc=com'
LDAP_USER_PASS = 'secret'
LDAP_OPTIONS = {}

def _new_connection():
    #conn = ldap.initialize(LDAP_URI)
    #conn.set_option(ldap.OPT_PROTOCOL_VERSION, 3)
    #conn.simple_bind_s(LDAP_USER_DN, LDAP_USER_PASS)
    conn = ldap.ldapobject.SmartLDAPObject(LDAP_URI, who=LDAP_USER_DN, cred=LDAP_USER_PASS)
    for optname, optvalue in LDAP_OPTIONS.items():
        if optname.startswith('OPT_'):
            optcode = getattr(ldap, optname)
            conn.set_option(optcode, optvalue)
        else:
            setattr(conn, optname, optvalue)
    _connections.conn = conn
    return conn

def initialize(uri, user_dn, user_pass, ldap_options=None):
    global LDAP_URI, LDAP_USER_DN, LDAP_USER_PASS, LDAP_OPTIONS
    LDAP_URI = uri
    LDAP_USER_DN = user_dn
    LDAP_USER_PASS = user_pass
    if ldap_options:
        LDAP_OPTIONS = ldap_options

def get_connection():
    """XXX"""
    try:
        conn = _connections.conn
    except AttributeError:
        return _new_connection()
    else:
        # XXX: Good way to test connection is still alive?
        # Necessary with SmartLDAPObject/ReconnectLDAPObject?
        try:
            conn.whoami_s()
        except ldap.LDAPError:
            # Connection is bad.
            return _new_connection()
        else:
            return conn
